import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
import { ProductService, ProductSearchParams } from '../shared/product.service';

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {

  private formModel: FormGroup;
  private categories: string[];
  constructor(public _productService: ProductService, fb: FormBuilder) {
    this.formModel = fb.group({
      title: ['', [Validators.minLength(3)]],
      price: [null, [this.positiveNumValidator]],
      category: [-1]
    });
  }

  ngOnInit() {
    this.categories = this._productService.getAllCategories();
  }
  onSubmit(e) {
    if (this.formModel.valid) {
      let title = this.formModel.get('title').value;
      let category = this.formModel.get('category').value;
      let price = this.formModel.get('price').value;
      this._productService.searchEvent.emit(new ProductSearchParams(title,
        price,
        category));
    }
  }
  positiveNumValidator(control: FormControl) {
    if (!control.value) {
      return null;
    }
    var intVal = parseInt(control.value);
    return intVal > 0 ? null : { positiveNum: true };
  }

}
